package com.example.teacherservice.service;

import com.example.teacherservice.dto.ClassAddDAO;
import com.example.teacherservice.dto.ClassDTO;
import com.example.teacherservice.dto.ClassRelationDTO;
import com.example.teacherservice.entity.*;
import com.example.teacherservice.entity.Class;
import com.example.teacherservice.repository.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class TeaClassService {
    private final TeaClassRepository teaClassRepository;
    private final ClassRepository classRepository;
    private final CouClassRepository couClassRepository;
    private final CourseRepository courseRepository;
    private final TeacherRepository teacherRepository;
    private final StuClassRepository stuClassRepository;


    public TeaClassService(TeaClassRepository teaClassRepository, ClassRepository classRepository, CouClassRepository couClassRepository, CourseRepository courseRepository, TeacherRepository teacherRepository, StuClassRepository stuClassRepository) {
        this.teaClassRepository = teaClassRepository;
        this.classRepository = classRepository;
        this.couClassRepository = couClassRepository;
        this.courseRepository = courseRepository;
        this.teacherRepository = teacherRepository;
        this.stuClassRepository = stuClassRepository;
    }

    public TeaClass saveTeaClass(TeaClass teaClass) {
        // 验证逻辑...
        return teaClassRepository.save(teaClass);
    }

    public List<TeaClass> findByTeaId(Long teaId) {
        return teaClassRepository.findByTeaId(teaId);
    }

    public List<TeaClass> getTeachersByClass(Long classId) {
        return teaClassRepository.findByClassId(classId);
    }

    // 创建班级
    public Class createClass(ClassDTO classDTO) {
        Class newClass = new Class();
        newClass.setClassName(classDTO.getClassName());
        newClass.setClassStuNum(classDTO.getClassStuNum());
        return classRepository.save(newClass);
    }

    @Transactional
    public Class createClassWithCourses(ClassAddDAO classAddDAO) {
        // 1. 创建班级基础信息
        Class newClass = createBasicClass(classAddDAO);

        // 2. 关联教师
        linkTeacher(newClass.getId(), classAddDAO.getTeacherId());

        // 3. 添加课程（如果有）
        if (classAddDAO.getCourseIds() != null && !classAddDAO.getCourseIds().isEmpty()) {
            addCoursesToClass(newClass.getId(), classAddDAO.getCourseIds());
        }

        return newClass;
    }

    private Class createBasicClass(ClassAddDAO dto) {
        Class cls = new Class();
        cls.setClassName(dto.getClassName());
        cls.setClassStuNum(Optional.ofNullable(dto.getClassStuNum()).orElse(0));
        return classRepository.save(cls);
    }

    private void linkTeacher(Long classId, Long teacherId) {
        TeaClass tc = new TeaClass();
        tc.setTeaId(teacherId);
        tc.setClassId(classId);
        teaClassRepository.save(tc);
    }

    @Transactional
    public void addCoursesToClass(Long classId, List<Long> courseIds) {
        Class cls = classRepository.findById(classId)
                .orElseThrow(() -> new IllegalArgumentException("班级不存在"));

        courseIds.forEach(courseId -> {
            Course course = courseRepository.findById(courseId)
                    .orElseThrow(() -> new IllegalArgumentException("课程不存在: " + courseId));

            if (!couClassRepository.existsByClassInfoIdAndCourseId(classId, courseId)) {
                CouClass cc = new CouClass();
                cc.setClassInfo(cls);
                cc.setCourse(course);
                cc.setStatus(1);
                couClassRepository.save(cc);
            }
        });
    }


    // 获取教师班级关系（简化版）
    // 在TeaClassService.java中添加以下方法
    public List<ClassRelationDTO> getEnhancedTeacherClassRelations(Long teacherId) {
        // 1. 获取教师班级关联关系
        List<TeaClass> teaClasses = teaClassRepository.findByTeaId(teacherId);

        // 2. 转换为增强版DTO
        return teaClasses.stream().map(tc -> {
            // 获取班级基础信息
            Class classInfo = classRepository.findById(tc.getClassId())
                    .orElseGet(() -> {
                        Class empty = new Class();
                        empty.setId(tc.getClassId());
                        return empty;
                    });

            // 获取教师信息
            Teacher teacher = teacherRepository.findById(tc.getTeaId())
                    .orElseGet(() -> {
                        Teacher empty = new Teacher();
                        empty.setTeaName("未知教师");
                        return empty;
                    });

            // 获取关联课程数量
            int courseCount = couClassRepository.countByClassInfoId(tc.getClassId());

            // 构建增强版DTO
            return new ClassRelationDTO(
                    classInfo.getId(),
                    classInfo.getClassName(),
                    teacher.getTeaName(),
                    Optional.ofNullable(classInfo.getClassStuNum()).orElse(0),
                    classInfo.getCreateTime(),
                    classInfo.getUpdateTime(),
                    courseCount,
                    classInfo.getDeleted() == 0 ? 1 : 0  // 状态转换
            );
        }).collect(Collectors.toList());
    }

    @Transactional
    public void deleteClassWithRelations(Long classId) {
        // 1. 检查班级是否存在
        Class classInfo = classRepository.findById(classId)
                .orElseThrow(() -> new IllegalArgumentException("班级不存在"));

        // 2. 删除班级-课程关联关系（CouClass）
        couClassRepository.deleteByClassInfoId(classId);

        // 3. 删除教师-班级关联关系（TeaClass）
        teaClassRepository.deleteByClassId(classId);

        // 4. 删除学生-班级关联关系（StuClass）
//        stuClassRepository.deleteByClassId(classId);

        // 5. 更新关联教师信息（将教师的class_id设为null）
        List<Teacher> teachers = teacherRepository.findByClassInfoId(classId);
        teachers.forEach(teacher -> {
            teacher.setClassInfo(null);
            teacherRepository.save(teacher);
        });

        // 6. 最后删除班级本身（硬删除）
//        classRepository.deleteById(classId);
    }

}